package com.lzyyj.gmis.base.webui.interceptor;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.lzyyj.common.BeanUtilsExt;
import com.lzyyj.gmis.base.service.IUserService;
import com.lzyyj.gmis.base.webui.ICurrentUserAware;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 当前用户检查拦截器，对请求的当前用户进行检查
 * 1、将当前用户信息注入线程变量池
 * 2、如果Action需要，将用户对象注入Action
 * @author Lzyyj
 */
@SuppressWarnings("serial")
public class CurrentUserCheckInterceptor extends AbstractInterceptor {
	
	private static Log log = LogFactory.getLog(CurrentUserCheckInterceptor.class);
	
	private IUserService<?,?> userService;

	public IUserService<?,?> getUserService() {
		return userService;
	}

	public void setUserService(IUserService<?,?> userService) {
		this.userService = userService;
	}

	/**
	 * session 中当前用户 key
	 */
	private String currentUserKey = "CurrentUser";

	public String getCurrentUserKey() {
		return currentUserKey;
	}

	public void setCurrentUserKey(String currentUserKey) {
		this.currentUserKey = currentUserKey;
	}

	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		Map<String, Object> session = ai.getInvocationContext().getSession();

		Object currentUser = session.get(currentUserKey);
		
		// 如果有注入兼容的userService，创建线程变量并保存当前用户信息
		if(userService!=null){
			Map<String, Object> map = userService.getThreadLocalMap(true);
			if (map!=null){
				map.put(userService.getCurrentUserKey(), currentUser);
			}
		}

		Object action = ai.getAction();
	
		// 如果已登录用户，并且 action 要求注入当前用户
		if (currentUser != null && action instanceof ICurrentUserAware) {
			// 判断用户对象类型与Action要求注入的类型是否匹配
			BeanUtilsExt.setProperty(action, "currentUser", currentUser);
		}
		return ai.invoke();
	}
	
}